import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import type { TodoItemType, TodoFilterType } from '@/types/storeType'

export const useTodoStore = defineStore(
  'todo',
  () => {
    const todos = ref<TodoItemType[]>([])
    const filter = ref<TodoFilterType>('all') // all | active | completed

    const filteredTodos = computed(() => {
      switch (filter.value) {
        case 'all':
          return todos.value
        case 'active':
          return todos.value.filter((todo) => !todo.completed)
        case 'completed':
          return todos.value.filter((todo) => todo.completed)
        default:
          return todos.value
      }
    })
    const totalCount = computed(() => todos.value.length)
    const activeCount = computed(() => todos.value.filter((todo) => !todo.completed).length)
    const completedCount = computed(() => totalCount.value - activeCount.value)

    function addTodo(text: string) {
      const todo: TodoItemType = {
        id: totalCount.value + 1,
        text,
        completed: false,
      }
      todos.value.push(todo)
    }

    function updateTodo(id: number, text: string) {
      const index = todos.value.findIndex((todo) => todo.id === id)
      todos.value[index].text = text
    }

    function removeTodo(id: number) {
      const index = todos.value.findIndex((todo) => todo.id === id)
      todos.value.splice(index, 1)
    }

    function toggleTodo(id: number) {
      const index = todos.value.findIndex((todo) => todo.id === id)
      todos.value[index].completed = !todos.value[index].completed
    }

    function clearCompleted() {
      todos.value = todos.value.filter((todo) => !todo.completed)
    }

    function setFilter(value: TodoFilterType) {
      filter.value = value
    }

    return {
      todos,
      filter,
      filteredTodos,
      totalCount,
      activeCount,
      completedCount,
      addTodo,
      updateTodo,
      removeTodo,
      toggleTodo,
      clearCompleted,
      setFilter,
    }
  },
  { persist: true },
)
